<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Weibo extends CI_Controller {
    
        function __construct() {
            parent::__construct();
            $this->load->library('sina_weibo/weibo_auth');
        }

	public function index() {}
        
        public function callback_auth() {
            // 用户点击了取消授权
            if ($this->input->get('error_code') == 21330) {
                return $this->load->view('weibo/callback_auth_success');
            }
            // 获取code
            $code = $this->input->get('code', true);
            if (!$code) {
                return api_failed('no_code_submit');
            }
            // 获取access信息 加载weibo client模块 并验证access token
            try {
                $access = $this->weibo_auth->get_access_token($code);
                $this->load->library('sina_weibo/weibo_client', 
                    array($access['access_token']));
            } catch (Exception $e) {
                return api_failed($e->getMessage());
            }
            // 存入session
            $access['expires_on'] = time() + $access['expires_in'];
            $this->session->sess_expiration = $access['expires_in'];
            $this->session->set_userdata('sina_weibo', $access);
            // 注册第一次授权的微博用户
            $this->load->model('user_model');
            $user = $this->user_model->get_user_by_wb_uid($access['uid']);
            $user_id = $user ? $user['user_id'] : $this->user_model->add_user(
                $access['uid'], $this->weibo_client->user['screen_name']);
            $this->session->set_userdata('uid', $user_id);
            $this->load->view('weibo/callback_auth_success');
        }
            
        public function callback_unauth() {
            user_do_login();
        }
        
        public function login() {
            redirect($this->weibo_auth->get_auth_url('all', 1));
        }
        
        public function logout() {
            user_do_login();
            $this->session->sess_destroy();
            $this->load->view('weibo/logout_success');
        }
}